package cn.tedu.csmall.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 网关gateway实现的第一个过滤器
 * 必须实现一个接口GlobalFilter
 * 如果想定义多个过滤器执行顺序,
 * 还要实现接口Ordered
 */
@Component
@Slf4j
public class MyFilter03 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //拿到头数据
        HttpHeaders headers = request.getHeaders();
        //从headers获取想要的头数据 Host 直接调用api
        InetSocketAddress host = headers.getHost();
        List<String> list = headers.get("Host");
        //打印数据
        log.info("从api方法getHost获取Host包含ip:{},和端口:{}",
                host.getHostName(),host.getPort());
        log.info("从api方法get('Host')获取数据:{}",list.get(0));
        List<String> list1 = headers.get("Authorization");
        ServerHttpResponse response = exchange.getResponse();
        //拿到这个值数据,但是有可能是空
        if (list1 == null || list1.size()==0){
            //JsonResult 准备 {"status":-999,"message":"您当前未认证","data":null}
            JsonResult result=new JsonResult();
            result.setState(-999);
            result.setMessage("您当前未认证");
            result.setData(null);
            String jsonData="{\"status\":-999,\"message\":\"您当前未认证\",\"data\":null}";
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.fromSupplier(() -> {
                return response.bufferFactory().wrap(jsonData.getBytes(StandardCharsets.UTF_8));
            }));
        }else {
            return chain.filter(exchange);//生成一个继续执行过滤器后的功能Mono;
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
